import selenium

from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from tyc_login_yanzheng.chaojiying import Chaojiying_Client
from PIL import Image
import time
from setting import *

def browser_initial():
    """"
    浏览器初始化,并打开天眼查界面（未登录状态）
    """
    chrome_options = ChromeOptions()
    # options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3756.400 QQBrowser/10.5.4039.400')
    chrome_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36')
    # options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})  # 不加载图片,加快访问速度
    if BROWSER_HEADLESS:
        chrome_options.headless = True
        chrome_options.add_argument('--no-sandbox')
    chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    if PROXY_IP_PATH:
        chrome_options.add_extension(PROXY_IP_PATH)
    driver = webdriver.Chrome(options=chrome_options)
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
          Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
          })
        """
    })
    driver.set_window_size(1920, 969)
    driver.get('https://www.tianyancha.com/advance/search')
    return driver


def login_cookie(browser):
    """
    从本地读取cookies并刷新页面,成为已登录状态
    """
    with open('tyc_login_yanzheng/tyc_cookie', 'r', encoding='utf8') as f:
        cookie_list = f.read().split('; ')
    # 往browser里添加cookies
    for cookie in cookie_list:
        # print(cookie)
        cookie_dict = {
            'domain': '.tianyancha.com',
            'name': cookie.split('=')[0],
            'value': cookie.split('=')[1],
            "expires": '',
            'path': '/',
            'httpOnly': False,
            'HostOnly': False,
            'Secure': False
        }
        browser.add_cookie(cookie_dict)
    browser.refresh()  # 刷新网页,cookies才成功


def yanzheng(driver):
    print('开始处理验证码。。。。。')
    if 'verify' not in driver.current_url:
        with open('test.html', 'w', encoding='utf8') as fp:
            fp.write(driver.page_source)
        print('没有验证码')
        return
    # 获取验证码窗口模块
    yzm_window = driver.find_element_by_xpath('/html/body/div[2]/div/div/div[3]/div[1]')
    # 截取全图
    driver.save_screenshot('tyc_login_yanzheng/img/quan.png')
    # 获取验证码窗口模块左上角坐标位置
    location = yzm_window.location
    # 获取验证码窗口模块右下角坐标位置
    size = yzm_window.size
    # 拼接我们要截取的窗口坐标
    crop_parms = (location['x'], location['y'], location['x'] + size['width'], location['y'] + size['height'])
    # print(crop_parms)
    # 使用PIL模块的Image类对图片操作截取验证码图片,保存
    image = Image.open('tyc_login_yanzheng/img/quan.png')
    image_part = image.crop(crop_parms)
    image_part.save('tyc_login_yanzheng/img/part.png')
    # chaojiying = Chaojiying_Client('zzx865086862', 'zzx19960529', '909508')
    chaojiying = Chaojiying_Client('13244828252', 'jueke.88', '917072')
    im = open('tyc_login_yanzheng/img/part.png', 'rb').read()
    result = chaojiying.PostPic(im, '9004')
    print(result)
    cuowuma = result[0]
    zuobiao = result[1]
    if not zuobiao:
        chaojiying.ReportError(cuowuma)
        time.sleep(3)
        return 'error'
    # print(zuobiao)
    if '|' in zuobiao:
        zuobiao_list = str(zuobiao).split('|')
        # print(zuobiao_list)
        for i in zuobiao_list:
            x = int(str(i).split(',')[0])
            y = int(str(i).split(',')[1])
            # print(x, y)
            ActionChains(driver).move_to_element_with_offset(yzm_window, x, y).click().perform()
    else:
        x = int(str(zuobiao).split(',')[0])
        y = int(str(zuobiao).split(',')[1])
        # print(x, y)
        ActionChains(driver).move_to_element_with_offset(yzm_window, x, y).click().perform()
    time.sleep(1.5)
    driver.find_element_by_xpath('//*[@id="submitie"]').click()
    time.sleep(1)
    while True:
        if '我们只是确认一下你不是机器人' in driver.page_source:
            chaojiying.ReportError(cuowuma)
            time.sleep(3)
            yanzheng(driver)
        else:
            break


def main():
    browser = browser_initial()
    login_cookie(browser)
    while True:
        browser.get('https://www.tianyancha.com/search?key=yier')
        # browser.get('https://antirobot.tianyancha.com/captcha/verify?return_url=https%3A%2F%2Fwww.tianyancha.com%2Fcompany%2F867595458&rnd=')
        time.sleep(1.6)
        res = yanzheng(driver=browser)
        if res != 'error':
            time.sleep(0.6)
            break
        print('获取坐标失败！重新获取验证码')
    browser.close()
    print('验证码处理完成！！！关闭浏览器引擎。。')

if __name__ == "__main__":
    browser = browser_initial()
    # browser = ''
    browser.get('https://qifu.baidu.com/?activeKey=SEARCH_IP')

    login_cookie(browser)
